import axios from 'axios';
import type { AxiosInstance, AxiosResponse } from 'axios';

// 创建 axios 实例
const service: AxiosInstance = axios.create({
    baseURL: import.meta.env.VITE_APP_API_BASE_URL,
    timeout: 15000,
    headers: {
        'Content-Type': 'application/json;charset=utf-8',
    },
});

// 请求拦截器
service.interceptors.request.use(
    (config) => {
        return config;
    },
    (error) => {
        console.error('Request error:', error);
        return Promise.reject(error);
    }
);

// 响应拦截器
service.interceptors.response.use(
    (response: AxiosResponse) => {
        const { code, message, data } = response.data;

        // 根据自己的业务逻辑修改
        if (code === 200) {
            return data;
        }

        // 处理特定的错误码
        switch (code) {
            case 401:
                // 未登录或 token 过期
                window.location.href = '/login';
                break;
            case 403:
                // 权限不足
                console.error('No permission');
                break;
            default:
                console.error(message || 'Error');
        }

        return Promise.reject(new Error(message || 'Error'));
    },
    (error) => {
        console.error('Response error:', error);
        return Promise.reject(error);
    }
);

// 封装 GET 请求
export function get<T>(url: string, params?: object): Promise<T> {
    return service.get(url, { params });
}

// 封装 POST 请求
export function post<T>(url: string, data?: object): Promise<T> {
    return service.post(url, data);
}

// 封装 PUT 请求
export function put<T>(url: string, data?: object): Promise<T> {
    return service.put(url, data);
}

// 封装 DELETE 请求
export function del<T>(url: string): Promise<T> {
    return service.delete(url);
}

export default service;
